<template>
    <div class="createPost-container">
        <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
            <div class="createPost-main-container">
                <el-form-item prop="name" style="margin-bottom: 40px;" label-width="100px" label="名称">
                    <el-input v-model="postForm.name" :rows="1" class="article-textarea" autosize placeholder="请输入店铺名称" />
                </el-form-item>
                <el-form-item prop="img_thumb" style="margin-bottom: 40px;" label-width="100px" label="缩略图">
                    <image-thumb-upload :field="'img_thumb'" :image-url="asset(postForm.img_thumb)" @fileChange="imgThumbChange" />
                </el-form-item>
                <el-form-item prop="img_display" label-width="100px" label="展示图">
                    <image-upload :field="'img_display'" :limit="1" :file-list="displayFileList" @fileListChange="displayFileListChange" />
                </el-form-item>
                <el-form-item prop="gallery" label-width="100px" label="轮播图">
                    <image-upload :field="'gallery'" :file-list="galleryFileList" @fileListChange="galleryFileListChange" />
                </el-form-item>
                <el-form-item :label="$t('城市')" prop="city" label-width="100px">
                    <v-distpicker :province="postForm.prov" :city="postForm.city" :area="postForm.district" @province="province" @city="city" @area="area" />
                </el-form-item>
                <el-form-item :label="$t('详细地址')" prop="address" label-width="100px">
                    <el-input v-model="postForm.address" style="width:400px" type="text" />
                </el-form-item>
                <el-row>
                    <el-col :span="8">
                        <el-form-item :label="$t('经度')" prop="lng" label-width="100px">
                            <el-input v-model="postForm.lng" style="width:140px" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('纬度')" prop="lat" label-width="100px">
                            <el-input v-model="postForm.lat" style="width:140px" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-button @click="chooseLocation">地图选取</el-button>
                    </el-col>
                </el-row>
                <el-form-item prop="tips" style="margin-bottom: 40px;" label-width="100px" label="预订提示">
                    <el-input v-model="postForm.tips" type="text" placeholder="请输入预订提示" />
                </el-form-item>
                <!-- <el-form-item :label="$t('预订协议：')" prop="contract" label-width="120px">
                    <tinymce ref="contract_editor" v-model="postForm.contract" :height="300" />
                </el-form-item> -->
                <el-form-item :label="$t('门店详情')" prop="detail" label-width="100px">
                    <tinymce ref="detail_editor" v-model="postForm.detail" :height="300" />
                </el-form-item>
                <el-button v-loading="loading" style="margin-left: 10px;" type="primary" @click="submitForm">
                    保存
                </el-button>
            </div>
        </el-form>

        <el-dialog width="750px" title="Gps位置" :visible.sync="dialogFormGps">
            <ChooseLocationBaidu @locationChange="locationChange" />
        </el-dialog>
    </div>
</template>

<script>
import { asset } from '@/common/js/url'
import { fetch, update, create } from '@/shop/api/store'

import VDistpicker from 'v-distpicker'
import ChooseLocationBaidu from '@/components/Map/ChooseLocationBaidu.vue'
import ImageThumbUpload from '@/platform/components/ImageThumbUpload'
import ImageUpload from '@/platform/components/ImageUpload'

import Tinymce from '@/components/Tinymce'

const defaultForm = {
    name: '',
    img_thumb: '',
    img_display: '',
    gallery: '',
    prov: '',
    city: '',
    district: '',
    address: '',
    lng: '',
    lat: '',
    tips: '',
    // contract: '',
    detail: ''
}

export default {
    name: 'StoreDetail',
    components: { VDistpicker, ImageThumbUpload, ChooseLocationBaidu, ImageUpload, Tinymce },
    props: {
        isEdit: {
            type: Boolean,
            default: false
        }
    },
    data() {
        const validateRequire = (rule, value, callback) => {
            if (value === '' || value === null || value === undefined) {
                this.$message({
                    message: rule.message,
                    type: 'error'
                })
                callback(new Error())
            } else {
                callback()
            }
        }
        return {
            id: 0,
            postForm: Object.assign({}, defaultForm),
            loading: false,
            userListOptions: [],
            rules: {
                name: [{ validator: validateRequire, message: '店铺名称为必填字段', trigger: 'blur' }],
                img_thumb: [{ validator: validateRequire, message: '缩略图为必填字段', trigger: 'blur' }],
                img_display: [{ validator: validateRequire, message: '展示图为必填字段', trigger: 'blur' }],
                city: [{ validator: validateRequire, message: '城市为必填字段', trigger: 'blur' }],
                address: [{ validator: validateRequire, message: '详细地址为必填字段', trigger: 'blur' }],
                lng: [{ validator: validateRequire, message: '经度为必填字段', trigger: 'blur' }],
                lat: [{ validator: validateRequire, message: '纬度为必填字段', trigger: 'blur' }],
                tips: [{ validator: validateRequire, message: '门店提示为必填字段', trigger: 'blur' }],
                // contract: [{ validator: validateRequire, message: '门店协议为必填字段', trigger: 'blur' }],
                detail: [{ validator: validateRequire, message: '门店详情为必填字段', trigger: 'blur' }]
            },
            tempRoute: {},
            dialogFormGps: false,
            displayFileList: [],
            galleryFileList: []
        }
    },
    created() {
        if (this.isEdit === true) {
            this.id = this.$route.query.id
            this.fetchData()
        }
    },
    methods: {
        validateRequire(rule, value, callback) {
            if (value === '' || value === null || value === undefined) {
                this.$message({
                    message: rule.message,
                    type: 'error'
                })
                callback(new Error())
            } else {
                callback()
            }
        },
        province(data) {
            this.postForm.prov = data.value
        },
        city(data) {
            this.postForm.city = data.value
        },
        area(data) {
            this.postForm.district = data.value
        },
        chooseLocation() {
            this.dialogFormGps = true
        },
        locationChange(data) {
            this.postForm.lng = data.longitude
            this.postForm.lat = data.latitude
            this.dialogFormGps = false
        },
        asset(path) {
            return asset(path)
        },
        imgThumbChange(data) {
            this.postForm.img_thumb = data.file_name
        },
        displayFileListChange(data) {
            if (data.fileList.length > 0) {
                this.postForm.img_display = data.fileList[0].name
            } else {
                this.postForm.img_display = ''
            }
        },
        galleryFileListChange(data) {
            let gallery_str = ''
            if (data.fileList.length > 0) {
                for (var i = 0; i < data.fileList.length; i++) {
                    if (i > 0) {
                        gallery_str += ';'
                    }
                    gallery_str += data.fileList[i].name
                }
            }
            this.postForm.gallery = gallery_str
        },
        fetchData() {
            fetch({ id: this.id }).then(response => {
                this.postForm.name = response.data.name
                this.postForm.img_thumb = response.data.img_thumb
                this.postForm.img_display = response.data.img_display
                this.postForm.gallery = response.data.gallery
                this.postForm.prov = response.data.prov
                this.postForm.city = response.data.city
                this.postForm.district = response.data.district
                this.postForm.address = response.data.address
                this.postForm.lng = response.data.lng
                this.postForm.lat = response.data.lat
                this.postForm.tips = response.data.tips
                this.postForm.contract = response.data.contract
                if (this.postForm.contract !== undefined && this.postForm.contract !== null && this.postForm.contract !== '') {
                    this.$refs['contract_editor'].setContent(this.postForm.contract)
                }
                this.postForm.detail = response.data.detail
                if (this.postForm.detail !== undefined && this.postForm.detail !== null && this.postForm.detail !== '') {
                    this.$refs['detail_editor'].setContent(this.postForm.detail)
                }
                if (response.data.img_display !== null && response.data.img_display !== '' && response.data.img_display !== undefined) {
                    this.displayFileList.push({
                        name: response.data.img_display,
                        url: asset(response.data.img_display)
                    })
                }
                if (response.data.gallery !== null && response.data.gallery !== '' && response.data.gallery !== undefined) {
                    const gallery = response.data.gallery.split(';')
                    for (var i = 0; i < gallery.length; i++) {
                        this.galleryFileList.push({
                            name: gallery[i],
                            url: asset(gallery[i])
                        })
                    }
                }
                // set page title
            }).catch(err => {
                console.log(err)
            })
        },
        submitForm() {
            this.$refs.postForm.validate(valid => {
                if (valid) {
                    this.loading = true
                    const data = Object.assign({}, this.postForm)
                    delete data.detail
                    if (this.isEdit === true) {
                        data.id = this.id
                        update(data, {detail: this.postForm.detail}).then(response => {
                            this.$notify({
                                title: '成功',
                                message: '修改成功',
                                type: 'success',
                                duration: 2000
                            })
                            // this.postForm.status = 'published'
                            this.loading = false
                            // this.$router.push('/store/index')
                        }).catch(err => {
                            console.log(err)
                            this.loading = false
                        })
                    } else {
                        create(data, {detail: this.postForm.detail}).then(response => {
                            this.$notify({
                                title: '成功',
                                message: '添加成功',
                                type: 'success',
                                duration: 2000
                            })
                            // this.postForm.status = 'published'
                            this.loading = false
                            this.$router.push('/store/index')
                        }).catch(err => {
                            console.log(err)
                            this.loading = false
                        })
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        draftForm() {
            if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
                this.$message({
                    message: '请填写必要的标题和内容',
                    type: 'warning'
                })
                return
            }
            this.$message({
                message: '保存成功',
                type: 'success',
                showClose: true,
                duration: 1000
            })
            this.postForm.status = 'draft'
        }
    }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
    position: relative;

    .createPost-main-container {
        padding: 40px 45px 20px 50px;

        .postInfo-container {
            position: relative;
            @include clearfix;
            margin-bottom: 10px;

            .postInfo-container-item {
                float: left;
            }
        }
    }

    .word-counter {
        width: 40px;
        position: absolute;
        right: 10px;
        top: 0px;
    }
}

.article-textarea ::v-deep {
    textarea {
        padding-right: 40px;
        resize: none;
        border: none;
        border-radius: 0px;
        border-bottom: 1px solid #bfcbd9;
    }
}
</style>
